<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { registerAPI, loginAPI } from '@/api/login'
import { useUserStore } from '@/stores/index'
import { useRouter } from 'vue-router'
const isRegister = ref(true)

// 用户仓库对象
const userStore = useUserStore()
// 路由对象
const router = useRouter()

// 注册表单对象
const registerRef = ref({})

// 自定义密码校验函数
const validateRepassword = (rules, value, callback) => {
  if (value !== registerFrom.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 注册表单校验规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名长度在5到10个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在6到15个字符', trigger: 'blur' },
    {
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,15}$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: validateRepassword,
      message: '两次输入的密码不一致',
      trigger: 'blur'
    }
  ]
}

// 注册表单数据
const registerFrom = ref({
  username: '',
  password: '',
  repassword: ''
})

// 注册逻辑
const onRegister = () => {
  // 整体校验
  registerRef.value.validate(async (valid) => {
    if (valid) {
      // 执行注册逻辑
      // 准备上传数据
      const data = {
        username: registerFrom.value.username,
        password: registerFrom.value.password,
        repassword: registerFrom.value.repassword
      }
      const res = await registerAPI(data)
      console.log(res)
      ElMessage.success(res.data.message)
    }
  })
}

// 登录表单数据
const loginFrom = ref({
  username: '',
  password: ''
})

// 登录表单对象
const loginRef = ref({})

// 登录逻辑
const onLogin = () => {
  // 整体校验
  loginRef.value.validate(async (valid) => {
    if (valid) {
      // 调用接口登录
      const res = await loginAPI(loginFrom.value)
      console.log(res)
      if (res.status === 200) {
        // 登录成功
        ElMessage.success(res.data.message)
        // 存储token
        userStore.setToken(res.data.token)
        // 跳转到首页
        router.push('/')
      }
    }
  })
}

// 监控注册登录切换
watch(isRegister, () => {
  registerFrom.value = { username: '', password: '', repassword: '' }
  loginFrom.value = { username: '', password: '' }
})
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        ref="registerRef"
        :model="registerFrom"
        :rules="registerRules"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="registerFrom.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerFrom.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="registerFrom.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="onRegister"
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <el-form
        ref="loginRef"
        size="large"
        autocomplete="off"
        :rules="registerRules"
        :model="loginFrom"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="loginFrom.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginFrom.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="onLogin"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
